import { getToken, setToken, removeToken } from '@/utils/auth'
import { login } from '@/api/user'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      UserInfo: JSON.parse(localStorage.getItem('UserInfo'))
    }
  },
  mutations: {
    // 存token
    updatedToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, user) {
      state.UserInfo = user
      // 储存到本地
      localStorage.setItem('UserInfo', JSON.stringify(user))
    },
    // 退出登录
    removeToken(state) {
      // 删除Vuex的token
      state.token = null
      state.UserInfo = {}
      removeToken()
      localStorage.removeItem('UserInfo')
    }

  },
  actions: {
    // 登录请求
    async loginPage(ctx, payload) {
      const res = await login(payload)
      ctx.commit('updatedToken', res.token.token)
      ctx.commit('setUserInfo', res.user)
    },
    // 退出登录
    logout(ctx) {
      ctx.commit('removeToken')
    }
  },
  getters: {}
}
